package com.zhiyou100.tools.mysql;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import javax.sql.DataSource;
import java.sql.*;

/**
 * @author yang
 * @packageName C3P0Tools
 * @className com.zhiyou100.tools
 * @Description TODO c3po 工具类
 * @date 7/28/20
 */
public class C3P0Tools {

    private static DataSource dataSource;

    static {
        dataSource = new ComboPooledDataSource();
        // 不写配置文件路径，必须在src下
        //dataSource=new ComboPooledDataSource("src/com/zhiyou100/javaweb/jdbc/learn/c3p0learn/c3p0-config.xml");
    }

    /**
     * @return java.sql.Connection
     * @Description TODO 获取链接
     * @name getCon
     * @param: []
     * @date 7/28/20 17:16
     * @author yang
     */
    public static Connection getCon() {
        try {
            return dataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    /**
     * @return void
     * @Description TODO 关闭链接
     * @name close
     * @param: [connection, statement, resultSet]
     * @date 7/28/20 17:16
     * @author yang
     */
    public static void close(ResultSet resultSet, Statement statement, Connection connection) {
        try {
            if (resultSet != null) {
                resultSet.close();
            }
            if (statement != null) {
                statement.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws SQLException {
        Connection con = getCon();
        System.out.println(con);
        assert con != null;
        PreparedStatement statement = con.prepareStatement("select * from Teacher;");
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
            String tname = resultSet.getString("tname");
            System.out.println(tname);
        }
        close(resultSet,statement,con);

    }
}
